// 1. 获取数据库引用
const db = wx.cloud.database().collection("image");
let file_id='';
let time ="";
let num = 0;
// 获取标准年月日
let getDate=function () {
  var date = new Date();
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return date.getFullYear() + '-' + month + '-' + day;
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    userinfo:'',
    imgPath:[],
    data:[]
  },
  // 点击轮播图 放大预览
  handlePrevewImage(e) {
    // 1 先构造要预览的图片数组 
    const urls = this.data.imgPath;
    // 2 接收传递过来的图片url
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    });

  },
  get_data(){
    wx.cloud.callFunction({
      name:"get_message",
      data:{
        db_name:"image",
        id:this.data.id
      },
      success:res=>{
       
        var data = [...res.result.data].reverse();
        wx.hideLoading();
       if(data.length==0){
         wx.showToast({
           title: '快来上传你的第一张图片吧',
           duration: 3000,
           icon: "none"
         })
       }
        var imgPath = data.map(item=>item.file_id);
        this.setData({
          data,
          imgPath
        });
        
        },
      fail:err=>{
        wx.hideLoading();
        wx.showToast({
          title: '请求图片失败',
          icon: "none"
        })
      }
    })
  },
  //提示用户下载
  downloadAllTip(){
    wx.showModal({
      title: '提示',
      content: '您确定要下载所有图片？',
      success: res => {
        if (res.confirm) {
          this.downloadAll()
        }
      },
      fail: err => {

      }
    })
  },
  downloadAll(){
    wx.getSetting({
      success:(res)=>{
       
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.openSetting({
            success(res) {
              //拒绝授权后重新提示授权，并授权成功
            }
          })
        } else {
          let length = this.data.imgPath.length;
          let num = 0;
          wx.showLoading({
            title: '正在下载中',
          })
          //
          this.data.imgPath.forEach(item=>{
          wx.cloud.downloadFile({
            fileID:item,
            success: (res) => {
              if (res.statusCode === 200) {
                let img = res.tempFilePath;
                //console.log(img)
                wx.saveImageToPhotosAlbum({
                  filePath: img,
                  success(res) {
                  num++;
                  if(num == length){
                    wx.hideLoading();
                    wx.showToast({
                      title: '保存成功',
                    })
                  }
                  },
                  fail(res) {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                })
              }
            },
            fail: err => {
              wx.showToast({
                title: '保存失败',
                icon: 'none',
                duration: 2000
              });
            }
          })
          })
          //
        }
      }
    })  
  },
  //提示用户删除
  deleteAllTip(){
    wx.showModal({
      title: '提示',
      content: '您确定要删除所有图片？',
      success:res=>{
        if(res.confirm){
        this.deleteAll()
        }
      },
      fail:err=>{

      }
    })
  },
  //删除所有图片
  deleteAll(){
    if(this.data.imgPath.length==0){
      wx.showToast({
        title: '暂无图片可删',
        icon:"none"
      })
      return;
    }
    wx.cloud.deleteFile({
      fileList: this.data.imgPath,
      success: res => {
        // handle success
        //console.log(res.fileList);
        //
       
        this.data.imgPath.forEach((item)=>{
         // console.log(item)
          db.where({ _openid: this.data.id}).remove({
            success: () => {
              
             
                this.setData({
                  imgPath: [],
                  data: []
                })
              
             },
            fail:err=>{
              wx.showToast({
                title: '删除图片失败',
                icon: "none"
              })
            }
          })
        })
        //
        wx.showToast({
          title: '删除成功',
        })
      },
      fail: err => {
        wx.showToast({
          title: '删除图片失败',
          icon: "none"
        })
      }
    })
  },
  choose_image(){
    //选择图片
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        wx.showLoading({
          title: '正在上传中...',
        })
        // tempFilePath可以作为img标签的src属性显示图片
        num = res.tempFilePaths.length;
        const tempFilePaths = res.tempFilePaths;
        tempFilePaths.forEach((item)=>this.upload_image(item));
      },
      fail:err=>{
        wx.showToast({
          title: '添加图片失败',
          icon: "none"
        })
      }
    })
  },
  //上传图片
  upload_image(tempFilePaths) {
    wx.cloud.uploadFile({
      cloudPath: new Date().getTime() +"."+ tempFilePaths.split("").reverse().join("").split(".")[0].split("").reverse().join(""),
      filePath: tempFilePaths, // 文件路径
      success: res => {
        num--;
        file_id = res.fileID;
        time = getDate();
       // console.log(res)
        db.add({
          data: {
            file_id,
            time
          },
          success: res => {
            if(num===0){
            this.get_data();
          wx.showToast({
            title: '上传成功',
          })
            }
            },
          fail: err => {
            wx.showToast({
              title: '添加图片失败',
              icon:"none"
            })
          }
        })
      },
      fail: err => {
        wx.showToast({
          title: '添加图片失败',
          icon: "none"
        })
      }
    })
  },
  //删除图片
  remove(e){
    wx.showModal({
      title: '提示',
      content: '您确定要删除？',
      success:(res)=> {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var index = e.currentTarget.dataset.index;
          var fileid = e.currentTarget.dataset.fileid
          db.doc(id).remove({
            success: () => {

              var data = this.data.data;
              data.splice(index, 1);
              this.setData({
                data
              })
              //删除云端的图片
              wx.cloud.deleteFile({
                fileList: [fileid],
                success: res => {
                  // handle success
                  console.log(res.fileList);
                  wx.showToast({
                    title: '删除成功',
                  })
                },
                fail: err=>{
                  wx.showToast({
                    title: '删除图片失败',
                    icon: "none"
                  })
                }
              })
            },
            fail: () => {
              wx.showToast({
                title: '删除图片失败',
                icon: "none"
              })
            }
          })
          //console.log('用户点击确定')
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })
    
    
  },
  //下载图片
  download(e){
    //
   var fileID = e.currentTarget.dataset.fileid;

    //
    wx.getSetting({
      success(res) {
      //  console.log(res)
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.openSetting({
            success(res) {
              //拒绝授权后重新提示授权，并授权成功
            }
          })
        } else {
         //
          wx.cloud.downloadFile({
            fileID,
            success: (res) => {
              if (res.statusCode === 200) {
                let img = res.tempFilePath;
                //console.log(img)
                wx.saveImageToPhotosAlbum({
                  filePath: img,
                  success(res) {
                    wx.showToast({
                      title: '保存成功',
                      icon: 'success',
                      duration: 2000
                    });
                  },
                  fail(res) {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                })
              }
            },
            fail: err => {
              wx.showToast({
                title: '保存失败',
                icon: 'none',
                duration: 2000
              });
            }
          }) 
         //
        }
      }
    })  
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    var userinfo = wx.getStorageSync("userinfo") || '';
    var id = wx.getStorageSync("id") || '';
    this.setData({
      userinfo,
      id
    });
    //如果用户登录了就初始化数据
    if (userinfo) {
      wx.showLoading({
        title: '加载中...',
      });
      this.get_data();
    }
  },  


  //下拉刷新事件
  onPullDownRefresh() {
    this.onShow();
    setTimeout(function(){
      wx.stopPullDownRefresh();
    },1500)
    
  },
  onLoad:function(){
   
    const backgroundAudioManager = wx.getBackgroundAudioManager()
    backgroundAudioManager.title = '夜空的寂静';
    
    backgroundAudioManager.singer = '赵海洋';
   // backgroundAudioManager.coverImgUrl = 'cloud://timefly-50m7e.7469-timefly-50m7e-1301575670/1589726158505.png';
    // 设置了 src 之后会自动播放
    backgroundAudioManager.src ="cloud://timefly-50m7e.7469-timefly-50m7e-1301575670/赵海洋 - 夜空的寂静.mp3"
    backgroundAudioManager.onEnded(function(){
      
    
        backgroundAudioManager.src = "cloud://timefly-50m7e.7469-timefly-50m7e-1301575670/赵海洋 - 夜空的寂静.mp3";
        backgroundAudioManager.title = '夜空的寂静';
        backgroundAudioManager.singer = '赵海洋';
       
   
    })
    
    

   
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    wx.showToast({
      title: '没有更多数据啦',
      icon:"none"
    }) 
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})